<template>
  <!-- 面包屑区域 -->
  <div class="bread">
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home/bookquery' }">图书查询</el-breadcrumb-item>
      <el-breadcrumb-item>图书借阅</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <!-- 卡片区域 -->
  <div class="content">
    <el-card>
      <!-- 借阅图书信息 -->
      <el-row>
        <el-col :span="22" style="color:blue;">归还图书信息</el-col>
        <el-col :span="1" class="goback" @click="router.back()">
          <span>返回 ></span>
        </el-col>
      </el-row><br>
      <el-row>
        <el-col :span="6">图书：《{{ book.bookname }}》</el-col>
        <el-col :span="6">作者： {{ book.author }}</el-col>
        <el-col :span="6">价格： {{ book.price }}</el-col>
        <el-col :span="4">库存：<span :class="book.stock ? 'green':'red'">{{ book.stock }}</span></el-col>
      </el-row><br>
      <el-row>图书状态：
        <span :class="book.stock ? 'green' : 'red'">{{book.stock ? '库存充足，可被借阅 √' : '库存不足，无法借阅 ×'}}</span>
      </el-row><br>
      <hr><br>
      <!-- 读者信息 -->
      <el-row style="color:blue;">读者信息</el-row><br>
      <el-row>
        <el-col :span="8">
          <el-input placeholder="请输入读者 id 或者姓名进行查询" size="large" v-model="input" class="input-with-select" @keydown.enter="searchReader">
              <template #append>
                <el-button icon="el-icon-search" @click="searchReader"/>
              </template>
          </el-input>         
        </el-col>
      </el-row><br>
      <el-row>
        <el-col :span="4">姓名：{{ reader.readername }}</el-col>
        <el-col :span="4">类型：{{ reader.readertype }}</el-col>
        <el-col :span="4">性别：{{ reader.sex }}</el-col>
        <el-col :span="4">最大可借数：{{ reader.max_num }}</el-col>
        <el-col :span="4">最大可借天数：{{ reader.days_num }}</el-col>
      </el-row><br>
      <el-row v-if="reader.readername">
        读者借阅状态：已借阅数量 {{ readerBorrowCount }}，剩余可借数&nbsp;<span :class="reader.max_num === readerBorrowCount ? 'red' : 'green'"> {{ reader.max_num - readerBorrowCount}}</span>，
        <span :class="reader.max_num === readerBorrowCount ? 'red' : 'green'">{{ reader.max_num === readerBorrowCount ? '不可借阅图书 ×' : '可借阅图书 √'}}</span>
      </el-row><br>
      <el-row v-if="reader.readername">
        已借当前图书数量：{{ readerBorrowNowCount }}
      </el-row><br>
      <hr><br>
      <!-- 填写借阅信息 -->
      <el-row style="color:blue;">填写借阅信息</el-row><br>
      <el-form ref="borrowInfoRef" :model="borrowForm" :rules="borrowRules" label-width="120px">
        <el-row>
          <el-form-item label="借阅时间" prop="borrow_date">
            <!-- <el-input v-model="borrowForm.borrowTime"/> -->
              <el-date-picker v-model="borrowForm.borrow_date" type="date" placeholder="请选择时间" :disabled="!book.stock ? true : false"/>
          </el-form-item>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6.5">
            <el-form-item label="归还时间" prop="back_date">
              <!-- <el-input v-model="borrowForm.backTime"/> -->
              <el-date-picker v-model="borrowForm.back_date" type="date" placeholder="请选择时间" :disabled="!book.stock ? true : false"/>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-button type="primary" @click="submit(borrowInfoRef)" :disabled="!book.stock ? true : false">提交</el-button>
          </el-col>
          <el-col class="borrowTips">Tips: 每次只能借一本书!</el-col>
        </el-row>

      </el-form>
    </el-card>
  </div>

</template>

<script setup>
import { ArrowRight } from '@element-plus/icons-vue'
import { onBeforeMount, onMounted, reactive, ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import { getReaderById, getReaderByName } from '@/network/reader.js'
import { borrowBook, getReaderBorrowCount, getReaderBorrowNowCount } from '@/network/borrow.js'
import { getBookById } from '@/network/book.js'
import { messageApi } from '../api/global';
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
// 从本地中获取到借阅书本信息
let book = ref({})
const input = ref('') // 搜索值
let reader = ref({})  // 读者信息
let readerBorrowCount = ref(null) // 读者借阅图书的数量
let readerBorrowNowCount = ref(null)  // 读者借阅当前图书的数量
const borrowInfoRef = ref(null) //借阅表单的引用
// 借阅信息
const borrowForm = reactive({
  book_id: book.value.id,
  reader_id: reader.value.id,
  borrow_date: new Date().toLocaleDateString(),
  back_date: '',
  if_back: 'no'
})
// 借阅信息的规则
const borrowRules = reactive({
  borrow_date: [
    { required: true, message: '请输入借阅时间', trigger: 'blur' },
    // { min: 1, max: 8, message: '请输入借阅时间', trigger: 'blur' }
  ],
  back_date: [
    { required: true, message: '请输入归还时间', trigger: 'blur' },
    // { max: 1, message: '请输入归还时间', trigger: 'blur' }
  ],
})


// 查询读者
const searchReader = async () => {
  messageApi().closeAll()
  try {
    if (!input.value) return messageApi('warning', '请输入读者 id 或姓名！')
    getReader()
  } catch(e) {
    messageApi('error', '查无此读者！')
  }
}

// 提交借阅信息
const submit = async (borrowInfoRef) => {
  if (reader.value.max_num === readerBorrowCount.value) return messageApi('error', '该读者借阅图书数量已满！')
  if (!reader.value.readername) return messageApi('warning', '请先确定为哪位读者借阅图书！')
  await borrowInfoRef.validate(async valid => {
    if (!valid) return
    // 处理借书时间和归还时间
    borrowForm.back_date = new Date(borrowForm.back_date).toLocaleDateString()
    borrowForm.borrow_date = new Date(borrowForm.borrow_date).toLocaleDateString()
    try{
      await ElMessageBox.confirm( `确认为读者 “${reader.value.readername}”，借阅该图书吗？`, '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })

      console.log('borrowForm',borrowForm);


      // 发起借书的请求（同时要更新页面上图书和读者的信息）
      const {data: res} = await borrowBook(borrowForm)
      if (res.code !== 200) return messageApi('error', res.msg)
      messageApi('success', res.msg)
      // 更新读者信息
      getReader()
      // 更新图书信息
      getBook(borrowForm.book_id)
    }catch(e) {
      messageApi('info', '已取消')
    }
  })
}

// 根据 id 或用读者姓名，查询读者信息
const getReader = async () => {
  if (Number.isInteger(Number(input.value))) {
    const { data: res} = await getReaderById(input.value)
    if (res.code !== 200) return messageApi('error', res.msg)
    reader.value = res.data
  } else {
    const { data: res} = await getReaderByName({readername: input.value})
    if (res.code !== 200) return messageApi('error', '查无此读者！')
    reader.value = res.data
  }
  borrowForm.reader_id = reader.value.id
  getRBorrowCount()
  getReaderBNC()
}

// 获取读者的借阅数量
const getRBorrowCount = async () => {
  const {data : resCount} = await getReaderBorrowCount({reader_id: reader.value.id})
  if (resCount.code !== 200 ) return messageApi('error', resCount.msg)
  readerBorrowCount.value = resCount.data
}

// 获取读者已借当前图书的数量
const getReaderBNC = async () => {
  const {data: res} = await getReaderBorrowNowCount({
    reader_id: reader.value.id,
    book_id: borrowForm.book_id
  })
  if (res.code !== 200) return messageApi('error', res.msg)
  readerBorrowNowCount.value = res.data
}

// 查找图书
const getBook = async (id) => {
  const {data: res} = await getBookById(id)
  if (res.code !== 200) return messageApi('error', res.msg)
  book.value = res.data
}

onMounted(async () => {
  // 进入借书界面时，就根据id请求图书信息数据
  const {data: res} = await getBookById(route.params.bookId)
  book.value = res.data
  borrowForm.book_id = book.value.id
})

</script>

<style lang="less" scoped>
.bread {
  margin: 15px 0 10px 15px;
  .el-breadcrumb .el-breadcrumb__item {
    font-size: 12px;
  }
}
.content {
  width: 100%;
  // height: 600px;
  margin: 0 15px;
  background: #fff;
  overflow: auto;
  width:  1300px;
}
.green {
  color: #2dad68  ;
}
.red{
  color: red;
}
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.borrowTips {
  color:rgba(136, 136, 136, 0.673);
  font-size:13px;
  margin-left:50px;
}
.goback {
  cursor: pointer;
  color: rgba(0, 0, 0, 0.54);
}
.goback:hover {
  color: black;
}
</style>